import scrapy, time
from w3lib.html import remove_tags
from kyqb_collection_spider.spiders.common import CommonSpider
from kyqb_collection_spider.items import KyqbCollectionSpiderItem


class LlNewsSpider(CommonSpider):
    name = 'll_news'
    start_urls = []
    custom_settings = {
        'ITEM_PIPELINES': {'kyqb_collection_spider.pipelines.NewImagesPipeline': 5,
                           'kyqb_collection_spider.pipelines.KyqbCollectionSpiderPipeline': 600},
    }
    base_url = 'https://www.ll.mit.edu/news?rdarea=All&rdgroup=All&type=All&author=All&tag=All&items_per_page=10&page={page_num}'
    for i in range(1, 24):
        start_urls.append(base_url.format(page_num=i))

    def parse(self, response):
        div_list = response.xpath('//*[@id="block-mitll-theme-content"]/div/div/div[1]/div')
        for div in div_list:
            href = response.urljoin(div.xpath('.//a/@href').extract_first())
            if not self.redis.sismember(self.name, href):
                yield scrapy.Request(url=href, callback=self.article)
            else:
                return None

    def article(self, response):
        try:
            item = KyqbCollectionSpiderItem()
            item['data_address'] = response.url
            item['website_name'] = 'LINCOLN LABORATORY'
            item['spider_name'] = self.name
            item['data_source_type'] = '科技网站'
            item['data_type'] = 'NEWS'
            item['collection_mode'] = 'spider'
            item['collection_time'] = time.strftime('%Y-%m-%d %H:%M:%S')
            timestamp = response.xpath('//*[@class="news-full__date"]/text()').extract_first().strip()
            item['publish_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(timestamp, "%B %d, %Y"))
            title = response.xpath('//*[@class="hero__page-title"]/text()').extract_first()
            item['title'] = remove_tags(title)
            item['abstract'] = response.xpath(
                '//*[@id="block-mitll-theme-content"]/div/div/div[2]/div/text()').extract_first().strip()
            postTags = [i.strip() for i in response.xpath(
                '//*[@id="block-mitll-theme-content"]/div/div/div[3]/div[1]/div[2]/a/text()').extract()]
            item['topic'] = '!@@!'.join(postTags)
            containers = response.xpath('//*[@class="news-full__body wysiwyg"]').extract()
            texts = []
            for container in containers:
                text = remove_tags(container).strip()
                texts.append(text)
            item['text'] = '\n'.join(texts)
            item['author'] = None
            image_urls = set()
            wysiwyg_images = response.css(".wysiwyg-image")
            for wysiwyg_image in wysiwyg_images:
                url=wysiwyg_image.xpath(".//img/@src").extract_first()
                image_urls.add('https://www.ll.mit.edu/'+url)
            item['image_urls'] = list(image_urls)
            yield item
        except Exception as e:
            self.logger.debug(f"采集错误:{response.url}\n{e}")
